// pages/category/category.js
import {Category} from 'category-model.js';
var category = new Category();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentMenuIndex:0,
    loading:true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this._loadData()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  _loadData(){
    category.getCategotyList(categoryData =>{
       this.setData({
        categoryTypeArr:categoryData
       });
       category.getChildCategoryArray(categoryData[0].id,(data) =>{
         this.setData({
          categoryProduct:data,
          categoryProduct0:data,
          loading:true
         })
       })
    })
  },
  //点击父选择分类
  changeCategory(event){
    var id = category.getDataSet(event,'id');
    var index = category.getDataSet(event,'index');
    this.setData({
      currentMenuIndex:index,
      loading:false
    })
    if(!this.isLoadedData(index)){
      this.getProductsByCategory(id,(data) =>{
        this.setData(
          this.getDataObjForBind(index,data)
          );
          this.setData({
            categoryProduct:this.data['categoryProduct'+index],
            loading:true
          })
      })
    }else{
     this.setData({
      categoryProduct:this.data['categoryProduct'+index],
      loading:true
     })
    }
  },
  //检查父类数组变量是否存在 categoryProduct+下标
  isLoadedData(index){
    if(this.data['categoryProduct'+index]){
      return true;
    }
     return false;
  },

   /**
   * 
   * @param id  分类id
   * @param  callback 回调方法
   * @data 该分类下所有商品信息
   */
  getProductsByCategory:function(id,callback){
    category.getChildCategoryArray(id,(data)=> {
      callback&&callback(data);
    });
  },
  //创建一个子类变量
  getDataObjForBind(index,data){
    var obj = {};
    obj['categoryProduct'+ index] = data;
    return obj;
  },
  //分类商品
  changeGoods(event){
    var id = category.getDataSet(event,'id');
    wx.navigateTo({
      url: '../list/list?id=' + id,
    });
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
   /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      loading:false
    })
    this._loadData();
  },
})